import axios from 'axios'
import {getToken, setToken,sha256} from '@/libs/util'
import Router from '../router'
import store from '@/store'
// import {date} from "mockjs/src/mock/random/date";

// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  const {statusText, status, request: {responseURL}} = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }

  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }

  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }

  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const {data, status} = res
      if (data.status && data.status == 401) {
        setToken('')
        Router.push({path: 'login'})
        return
      }
      return {data, status}
    }, error => {
      if (error.response && error.response.status == 401) {
        setToken('')
        Router.push({path: 'login'})
        return
      }
      return Promise.reject(error)
    })
  }

  request(options) {
    var param = "{}"
    if (options.method=='get'){
      var ul=options.url.split("?")
      if (ul.length>1){
        param=ul[1]
      }
    }else if (options.method=='post'||options.method=='put'||options.method=='delete'){
      if (options.data && options.data != undefined) {
        param = JSON.stringify(options.data)
      }else if (options.param && options.param != undefined){
        param = JSON.stringify(options.param)
      }else if(options.query && options.query != undefined){
        param = JSON.stringify(options.query)
      }
    }

    var nowTm=parseInt(new Date().valueOf() / 1000)
    var data={headers: {'authorization': 'Bearer ' + getToken(), 'x-userId': JSON.parse(localStorage.getItem( 'user' )).userId, 'x-tm': nowTm, 'x-sign': sha256(param,nowTm)}}
    var mid= Router.history.current.meta.mid
    if (mid!=undefined){
      data={headers: {'authorization': 'Bearer ' + getToken(), 'x-userId': JSON.parse(localStorage.getItem( 'user' )).userId, 'x-tm': nowTm, 'x-sign': sha256(param,nowTm),"mid":mid}}
    }
    const instance = axios.create(data)
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}

export default HttpRequest
